//
//  WBNetworkManager + Extension.swift
//  czWB
//
//  Created by Qing on 2018/7/17.
//  Copyright © 2018年 成哥哥. All rights reserved.
//

import Foundation
import SVProgressHUD

// MARK: - 封装新浪微博的网络请求方法
extension WBNetworkManager {
    
    /// 加载微博数据字典
    ///
    /// - Parameters:
    ///   - since_id: 返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    ///   - max_id: 返回ID小于或等于max_id的微博，默认为0。
    ///   - completion: 完成回调[list: 字典数据/是否成功]
    func statuseList(since_id: Int64 = 0, max_id: Int64 = 0, completion: @escaping (_ list: [String: Any]?, _ isSuccess: Bool) -> ())  {

        /// 获取当前登录用户及其所关注（授权）用户的最新微博- get - [http://open.weibo.com/wiki/2/statuses/home_timeline](http://open.weibo.com/wiki/2/statuses/home_timeline)
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"

        let params = ["since_id": since_id,
                      "max_id": max_id]
        
        tokenRequest(url: urlString, paramenters: params) { (json, isSuccess) in

//            通过打印json查看要返回的数据类型，{}：字典, ()：数组
//            print(json)
//            从json中获得"statuses" 字典数据
//            如果 as? 失败，则返回nil
            let result = json as? [String: Any]
            completion(result, isSuccess)
            
        }
    }
    
}


// MARK: - 用户详细信息相关方法
extension WBNetworkManager {
    
    /// 加载用户详细信息方法
    func loadUserIfon(completion:@escaping (_ dict:[String: Any]) ->())  {
        
        /// - set: 请求网址[https://api.weibo.com/2/users/show.json](https://api.weibo.com/2/users/show.json)
        let urlString  = "https://api.weibo.com/2/users/show.json"
        
//        如果没有uid与token一起被保存，如果没有uid则说明没有登录。
        guard  let uid = userAcount.uid else {
            return
        }
        
        let param = ["uid": uid]
        
        tokenRequest(url: urlString, paramenters: param) { (results, isSuccess) in
            
            completion(results as? [String: Any] ?? [:])
            
        }
        
    }
    
}

// MARK: - accessToken相关方法
extension WBNetworkManager {
    
    /// 使用accessToken 加载用户帐户信息方法
    ///
    /// - Parameters:
    ///   - code: code
    ///   - completion: 完成回调[是否成功]
    func loadAccessToken(code: String, completion: @escaping (_ isSuccess: Bool)-> ()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let param = ["client_id": WBAppKey,
                     "client_secret": WBAppSecret,
                     "grant_type": "authorization_code",
                     "code": code,
                     "redirect_uri": WBAuthorize,]
        
        WBNetworkManager.shared.request(Methou: .POST, url: urlString, paramenters: param) { (results, isSuccess) in
//            print("token\(results)")
            
//            数据转模型,yymodel的写法
//            self.userAcount.yy_modelSet(withJSON: results as? [String: Any] ?? [:])

//            1.json转字典
            guard let data = results as? [String: Any] else {

                print("accessToken Json转字典失败")

                return
            }

//            print("josn用户信息模型---\(data)")

//            2.字典转模型
            guard let access_token = data["access_token"] as? String,
                let expires_in = data["expires_in"] as? TimeInterval,
                let uid = data["uid"] as? String
//                let expiresDate = data["expiresDate"] as? Date

            else {
                print("WBNetworkManager + Extension 字典转模型失败")
                return
            }

//            3.保存数据
            self.userAcount.access_token = access_token
            self.userAcount.expires_in = expires_in
            self.userAcount.uid = uid
            
//            打印出来看看有没有保存成功
//            print("用户信息模型\(self.userAcount)")
//            print("过期时间\(self.userAcount.expiresDate)")
            

            
            self.loadUserIfon(completion: { (dict) in
                
//                如果没有拿到这两个信息，则说明请求没有成功。
                guard let avatar_large = dict["avatar_large"] as? String,
                    let screen_name = dict["screen_name"] as? String else {
                        return
                }
                
                self.userAcount.avatar_large =  avatar_large
                self.userAcount.screen_name = screen_name
                
//                print(self.userAcount)

//              用字典设置模型
                self.userAcount.saveAccount()
                
//              回调，网络请求成功则成功。网络请求失败则失败。
                completion(isSuccess)

            })

        }
    }
}
